from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client


@deconstructible
class MyStorage(Storage):
    def __init__(self, base_url=None):
        if not base_url:
            base_url = settings.BASE_URL
        self.base_url = base_url

    def open(self, name, mode='rb'):
        pass

    def save(self, name, content, max_length=None):
        """

        :param name: 图片名字
        :param content: 图片内容
        :param max_length: 最大的上传量
        :return: 返回名字
        """
        #创建对象
        clent=Fdfs_client('utils/fdfs/clent.conf')

        #上传文件
        result=clent.upload_by_buffer(content.read())

        #判断是否上传成功
        if result['Status']=='Upload successed.':
            return result['Remote file_id']
        else:
            raise Exception("图片上传失败")

    def exists(self, name):
        return False

    def url(self, name):
        return self.base_url+name